<?php
namespace api\home\controller;

use think\Db;
use think\Validate;
use api\common\controller\RestBaseController;
use think\Request;
use fast\Http;

class CycleController extends RestBaseController
{
    public function __construct()
    {
        parent::__construct();
        set_time_limit(0);
    }

    protected $beforeActionList = [
        'checkIp'
    ];

    protected function checkIp()
    {
        $request = Request::instance();
        $ip = $request->ip();
        //file_put_contents('ip.txt', $ip);
        if($ip !='54.178.199.210'){
            $this->error('未知错误');
        }
    }
    /*邀请奖励发放30天*/
    public function reward($miner_id=null){
        //排除周末
        $now = time();
        // if((date('w',strtotime($now)) == 0)){
        //     return false;
        // }
        if($miner_id){
             $all_cycle_miner = Db::name('user_miner')
            // ->where('reward_day','<',30)
            // ->where('miner_cat','exp',' IN (1,3) ')
            // ->where('miner_id','>',0)
            ->where('id',$miner_id)
            ->where('status',1)
            ->select(); 
        }else{
            $all_cycle_miner = Db::name('user_miner')
            ->where('reward_day','<',30)
            //->where('miner_cat','exp',' IN (1,3) ')
            //->where('miner_id','>',0)
            ->where('status',1)
            ->select(); 
        }
        if($all_cycle_miner){
            $reward_count = 0;
            $miner_count = 0;
            // 启动事务
            Db::startTrans();
            try{
                foreach ($all_cycle_miner as $key => $value) 
                {
                    $invite = Db::name('invite')->where('user_id',$value['user_id'])->find();
                    $status = Db::name("user")->where('id', $value['user_id'])->value('status');
                    if($status!='normal'){
                        continue;
                    }
                    $all_parentid = explode(',', $invite['path']);
                    $total_output_value = $value['arithmetic_value']*24;
                    $all_invite_user = Db::name('user')
                    ->where('id','in',$all_parentid)
                    ->where('status','normal')
                    ->field('id,total_zt_person,movable_wallet,ipfs_wallet')
                    ->order('id desc')
                    ->select();  
                    // echo Db::name('user')->getlastsql();
                    // die;
                    foreach ($all_invite_user as $k => $v)
                    {    
                            $generation = $k;
                            $invite_reward = 0;
                            if($v['id'] != $value['user_id']){
                                switch ($generation) {
                                    case 1:
                                        if($v['total_zt_person']>=1){
                                           $range = 0.2;
                                           $invite_reward = $total_output_value*$range; 
                                        }
                                        break;
                                    case 2:
                                        if($v['total_zt_person']>=2){
                                            $range = 0.5;
                                            $invite_reward = $total_output_value*$range; 
                                        }
                                        break;
                                    case 3:
                                        if($v['total_zt_person']>=3){
                                            $range = 0.4;
                                            $invite_reward = $total_output_value*$range; 
                                        }
                                        break;
                                    case 4:
                                        if($v['total_zt_person']>=4){
                                            $range = 0.3;
                                            $invite_reward = $total_output_value*$range; 
                                        }
                                        break;
                                    case 5:
                                    case 6:
                                    case 7:
                                    case 8:
                                    case 9:
                                    case 10:
                                        if($v['total_zt_person']>=5){
                                            $range = 0.1;
                                            $invite_reward = $total_output_value*$range; 
                                        }
                                        break;
                                    case 11:
                                    case 12:
                                    case 13:
                                    case 14:
                                    case 15:
                                    // case 16:
                                    // case 17:
                                    // case 18:
                                    // case 19:
                                    // case 20:
                                        if($v['total_zt_person']>=10){
                                            $range = 0.05;
                                            $invite_reward = $total_output_value*$range; 
                                        }
                                        break;
                                    default:
                                        // if($v['total_zt_person']>=15){
                                        //     $range=0.01;
                                        //     $invite_reward = $total_output_value*$range; 
                                        // }
                                        break;
                                }
                                //邀请奖励资金明细
                                $invite_reward = round($invite_reward,5);
                                if($invite_reward>0){
                                    $last_invite_reward = $invite_reward*0.8;
                                    $user_balance_log[0]['user_id']    = $v['id'];
                                    $user_balance_log[0]['amount']     = $last_invite_reward;
                                    $user_balance_log[0]['before']     = $v['movable_wallet'];
                                    $user_balance_log[0]['after']      = $v['movable_wallet']+$last_invite_reward;
                                    $user_balance_log[0]['remark']     = '邀请奖励';
                                    $admin_remark = "代数[{$generation}],直推人数[{$v['total_zt_person']}],来源用户ID[{$value['user_id']}],来源矿机ID[{$value['id']}],来源矿机产量[{$total_output_value}],奖励比例[$range]";
                                    $user_balance_log[0]['admin_remark']   = $admin_remark;
                                    $user_balance_log[0]['type']       = 1;
                                    $user_balance_log[0]['log_type']   = 3;
                                    $user_balance_log[0]['source']     = 4;
                                    $user_balance_log[0]['createtime'] = time();

                                    $ipfs_reward = $invite_reward*0.2;
                                    $user_balance_log[1]['user_id']    = $v['id'];
                                    $user_balance_log[1]['amount']     = $ipfs_reward;
                                    $user_balance_log[1]['before']     = $v['ipfs_wallet'];
                                    $user_balance_log[1]['after']      = $v['ipfs_wallet']+$ipfs_reward;
                                    $user_balance_log[1]['remark']     = '邀请奖励';
                                    $admin_remark = "代数[{$generation}],直推人数[{$v['total_zt_person']}],来源用户ID[{$value['user_id']}],来源矿机ID[{$value['id']}],来源矿机产量[{$total_output_value}],奖励比例[$range]";
                                    $user_balance_log[1]['admin_remark']   = $admin_remark;
                                    $user_balance_log[1]['type']       = 1;
                                    $user_balance_log[1]['log_type']   = 7;
                                    $user_balance_log[1]['source']     = 4;
                                    $user_balance_log[1]['createtime'] = time();

                                    Db::name('user')->where('id',$v['id'])
                                    ->update([
                                    'movable_wallet' => Db::raw('movable_wallet+'.$last_invite_reward),
                                    'ipfs_wallet' => Db::raw('ipfs_wallet+'.$ipfs_reward),
                                    'total_invite_reward' => Db::raw('total_invite_reward+'.$invite_reward),
                                    ]);
                                    Db::name('user_balance_log')->insertAll($user_balance_log);
                                    $reward_count++;
                                }
                            }

                    }
                  Db::name('user_miner')
                  ->where('id',$value['id'])
                  ->setInc('reward_day');
                  $miner_count++;      
                } 

                // 提交事务
                Db::commit(); 
                $this->success("运行完毕",['miner_count'=>$miner_count,'reward_count'=>$reward_count]); 
            }catch (\think\Exception\DbException $exception){
                Db::rollback();
                $this->error($exception->getMessage());
            }
        }else{
            $this->error('矿机不存在');
        }
    }

        /*1、矿机产矿收益及动态推广收益全部进入活动钱包*/
    public function miner(){
        //排除周末
        $now = time();
        // if((date('w',strtotime($now)) == 0)){
        //     return false;
        // }
        //满足运行时间
        $all_cycle_miner = Db::name('user_miner')
        ->where('createtime','<=',$now)
        //->where('miner_id','>',0)
        ->where('status',1)
        ->select();
        $i = 0;
        foreach ($all_cycle_miner as $key => $value) {
            $status = Db::name("user")->where('id', $value['user_id'])->value('status');
            if($status!='normal'){
                continue;
            }
            //矿机产生收益记录
            $user_output_log['user_id']   = $value['user_id'];
            $user_output_log['miner_id']  = $value['miner_id'];
            $user_output_log['miner_cat'] = $value['miner_cat'];
            $user_output_log['output']    = $value['arithmetic_value'];
            $user_output_log['createtime'] = time();
            // // 启动事务
            Db::startTrans();
            try{
                //if($value['miner_id']>0){
                    Db::name('user_output_log')->insert($user_output_log);
                //}
                //统计矿机产矿量
                $output = Db::name('user_output_log')->where('miner_id',$value['miner_id'])->sum('output');
                //矿机信息
                switch ($value['miner_type']){
                    case 0:
                        $limit = 2;
                        break;
                    case 1:
                        $limit = 2.1;
                        break;
                    case 2:
                        $limit = 2.2;
                        break;
                    case 3:
                        $limit = 2.5;
                        break;
                    default:
                        $limit = 2;
                        break;
                }
                $limit_money = $value['price']*$limit;
                if($output >= $limit_money){
                    Db::name('user_miner')->where('miner_id',$value['miner_id'])->setField('status',0);
                }
                //更新矿机运行次数
//                if(($value['runed_cycle']+1)==$value['run_cycle']){
//                    Db::name('user_miner')
//                    ->where('id',$value['id'])
//                    ->update([
//                    'runed_cycle'  => Db::raw('runed_cycle+1'),
//                    'updatetime'   =>time(),
//                    'status'       =>0,
//                    ]);
//                }else{
//                   Db::name('user_miner')
//                    ->where('id',$value['id'])
//                    ->update([
//                    'runed_cycle'  => Db::raw('runed_cycle+1'),
//                    'updatetime'   =>time(),
//                    ]);
//                }
                // 提交事务
                Db::commit(); 
                $i++;
            } catch (\think\Exception\DbException $exception){
                Db::rollback();
                //$this->error($exception->getMessage());
            }
            
        }
        $this->success("运行完毕",['count'=>$i]);
    }

    // public function transfer(){
    //     $transfer_log = Db::name('block_chain_trade')
    //     ->where(['status'=>2])
    //     ->group('address')
    //     ->field("sum(amount) as total,address")
    //     ->select();
    //     foreach ($transfer_log as $key => $value) {
    //         Db::name('user')->where()
    //     }
    //     echo Db::name('block_chain_trade')->getlastsql();
    //     die;
    //     // 启动事务
    //     //Db::startTrans();
    // }

    //获取USDT汇率
    public function getusdtmarket()
    {
        $Http = new \fast\Http;
        $result = $Http->get('http://api.zb.cn/data/v1/trades?market=usdt_qc');
        $result = json_decode($result,true);
        $item = $result[0];
        Db::name('config')->where(['group'=>'exchange','name'=>'usdt'])->update([
            'value'=>round($item['price'],2)
        ]);
        $this->success("运行完毕",['item'=>$item]);  
    }

}
